package com.ruoyi.workflow.service.impl;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.workflow.domain.CarPackageAudit;
import com.ruoyi.workflow.domain.vo.CarPackageAuditVo;
import com.ruoyi.workflow.domain.vo.HistoricActivity;
import com.ruoyi.workflow.service.ICarPackageAuditService;
import com.ruoyi.workflow.service.IDoneTaskService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.utils.bean.BeanUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class DoneTaskServiceImpl implements IDoneTaskService {

    private final TaskService             taskService;
    private final ICarPackageAuditService carPackageAuditService;
    private final ISysUserService         userService;
    private final HistoryService          historyService;

    public DoneTaskServiceImpl(ICarPackageAuditService carPackageAuditService, ISysUserService userService, HistoryService historyService, TaskService taskService) {
        this.carPackageAuditService = carPackageAuditService;
        this.userService            = userService;
        this.historyService         = historyService;
        this.taskService            = taskService;
    }

    /**
     * 查询我的已办任务列表
     */
    @Override
    public TableDataInfo selectTodoList(CarPackageAudit carPackageAudit) {
        // 1. 接收前端的分页参数
        TableDataInfo info = new TableDataInfo();
        info.setCode(HttpStatus.SUCCESS);

        // 2. 以当前用户作为负责人, 统计任务个数
        String loginUsername = SecurityUtils.getUsername();
        long total;
        if (carPackageAudit.getParams().get("beginCreateTime") == null) {
            total = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(loginUsername)
                    .finished()
                    .count();
        } else {
            total = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(loginUsername)
                    .finished()
                    .taskCreatedAfter(DateUtils.dateTime(DateUtils.YYYY_MM_DD, carPackageAudit.getParams().get("beginCreateTime") + ""))  // 在给定时间之后
                    .taskCreatedBefore(DateUtils.dateTime(DateUtils.YYYY_MM_DD, carPackageAudit.getParams().get("endCreateTime") + ""))   // 在给定时间之前
                    .count();
        }
        info.setTotal(total);

        // 3. 如果数量为 0, 返回空数据
        if (total == 0) {
            info.setRows(Collections.emptyList());
            return info;
        }

        // 4. 如果有数据, 构建分页条件
        PageDomain pageDomain = TableSupport.buildPageRequest();
        int startIndex = (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();

        // 5. 以当前用户作为负责人, 查询所有已经完成的任务列表
        List<HistoricTaskInstance> taskList;
        if (carPackageAudit.getParams().get("beginCreateTime") != null) {
            taskList = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(loginUsername)
                    .finished()
                    .taskCreatedAfter(DateUtils.dateTime(DateUtils.YYYY_MM_DD, carPackageAudit.getParams().get("beginCreateTime") + ""))  // 在给定时间之后
                    .taskCreatedBefore(DateUtils.dateTime(DateUtils.YYYY_MM_DD, carPackageAudit.getParams().get("endCreateTime") + ""))   // 在给定时间之前
                    .orderByTaskCreateTime().desc()
                    .listPage(startIndex, pageDomain.getPageSize());
        } else {
            taskList = historyService.createHistoricTaskInstanceQuery()
                    .taskAssignee(loginUsername)
                    .finished()
                    .orderByTaskCreateTime().desc()
                    .listPage(startIndex, pageDomain.getPageSize());
        }

        // 6. 创建一个集合, 用于存储最终返回的数据列表
        List<CarPackageAudit> auditList = new ArrayList<>();

        // 7. 遍历任务列表
        for (HistoricTaskInstance task : taskList) {
            // 8. 基于任务对象, 得到流程实例 id, 查询流程实例对象
            HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();

            // 9. 基于流程实例对象, 得到业务标识, 基于业务标识查询审核记录对象
            CarPackageAudit audit = carPackageAuditService.getById(Long.valueOf(instance.getBusinessKey()));

            // 10. 将审核记录对象的数据拷贝到 vo 中, 并补充相应字段(完成时间/任务名称/负责人)
            CarPackageAuditVo vo = new CarPackageAuditVo();
            BeanUtils.copyBeanProp(vo, audit);

            vo.setFinishedTime(task.getEndTime());
            vo.setTaskId(task.getId());
            vo.setTaskName(task.getName());
            // 负责人 => 我的已办, 所以负责人就是当前用户
            vo.setAuditors(SecurityUtils.getLoginUser().getUser().getNickName());

            // 11. 查询任务的创建人并设置到审核记录
            SysUser creator = userService.selectUserById(Long.valueOf(audit.getCreatorId()));
            vo.setCreator(creator);

            // 12. 将 vo 对象加入返回的集合中
            auditList.add(vo);
        }
        // 13. 返回分页数据
        info.setRows(auditList);
        return info;
    }

    @Override
    public List<HistoricActivity> selectHistoryList(String instanceId) {
        // 1: 基于 流程实例ID 查询 历史任务(已完成)列表
        List<HistoricActivityInstance> instanceList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(instanceId)
                .activityType("userTask")
                .orderByHistoricActivityInstanceStartTime().asc()
                .list();
        // 2: 遍历历史任务集合, 基于 任务ID 查询 批注信息
        List<HistoricActivity> historicActivityList = new ArrayList<>(instanceList.size());

        for (HistoricActivityInstance instance : instanceList) {
            HistoricActivity activity = new HistoricActivity();
            com.ruoyi.common.utils.bean.BeanUtils.copyBeanProp(activity, instance);

            // 批注信息
            List<Comment> commentList = taskService.getTaskComments(instance.getTaskId(), "comment");
            if (!CollectionUtils.isEmpty(commentList)) {
                activity.setComment(commentList.get(0).getFullMessage());
            }

            // 负责人名词
            SysUser sysUser = userService.selectUserByUserName(instance.getAssignee());
            if (sysUser != null) {
                activity.setAssigneeName(sysUser.getNickName());
            }

            historicActivityList.add(activity);
        }
        return historicActivityList;
    }
}
